package com.youyicloud.api;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.thoughtworks.xstream.core.util.Base64Encoder;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(value="验证码接口")
public class KaptchaApi {
	@Autowired
	private DefaultKaptcha defaultKaptcha;


	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation("图形验证码接口")
	@RequestMapping(value="/getVrifyCode",method= {RequestMethod.GET,RequestMethod.POST})
	public Map getVrifyCode() throws Exception {
		// 生成文字验证码
		String text = defaultKaptcha.createText();
		// 生成图片验证码
		ByteArrayOutputStream outputStream = null;
		BufferedImage image = defaultKaptcha.createImage(text);
		outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);
		// 对字节数组Base64编码
		Base64Encoder encoder = new Base64Encoder();
		String imgStr = encoder.encode(outputStream.toByteArray());
		Map resultMap = new HashMap();
		resultMap.put("imgStr", "data:image/jpeg;base64,"+imgStr);
		return resultMap;
	}
}
